<template>
  <div>
    <searchBox @handleSearch="handleSearch" @handleReset="handleReset">
      <el-form :inline="true" :model="searchFrom.param" label-width="auto" ref="serveRef">
        <el-form-item label="服务商" prop="cloudServerProviderId">
          <el-select v-model="searchFrom.param.cloudServerProviderId" placeholder="请选择" style="width: 185px" clearable>
            <el-option v-for="dict in sys_provider" :key="dict.value" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务商账号" prop="cloudServerId">
          <el-select v-model="searchFrom.param.cloudServerId" placeholder="请选择" style="width: 185px" clearable>
            <el-option v-for="dict in sys_account" :key="dict.value" :label="dict.username"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家" prop="newCountryId">
          <el-tree-select v-model="searchFrom.param.newCountryId" placeholder="请选择" :data="sys_country"
            style="width: 185px" :props="defaultProps" clearable />
        </el-form-item>
        <el-form-item label="当前状态" prop="status">
          <el-select v-model="searchFrom.param.status" placeholder="请选择" style="width: 185px" clearable>
            <el-option v-for="dict in sys_status_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </searchBox>
    <el-button type="primary" @click="addService" class="mb8">新增</el-button>

    <el-table :data="tableData" style="height: calc(100vh - 320px)" :row-style="rowStyle" v-loading="loading">
      <el-table-column prop="id" label="服务器ID" width="100" />
      <el-table-column prop="cloudServerProviderName" label="服务商" />
      <el-table-column prop="cloudServerName" label="服务商账号" />
      <el-table-column prop="serverNo" label="服务器编号" />
      <el-table-column prop="mainIp" label="主IP" width="150" />
      <el-table-column label="国家 - 城市" prop="countryCity" width="300" />
      <el-table-column prop="name" label="开始时间 - 到期时间" align="center" width="400">
        <template #default="scope">
          <el-space :size="10" spacer="-">
            <el-text :type="scope.row.current"> {{ scope.row.newInitiate }}</el-text>
            <el-text :type="scope.row.current"> {{ scope.row.newExpire }}</el-text>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="到期状态">
        <template #default="scope">
          <span v-if=" scope.row.current"> {{ scope.row.current === 'warning' ? "即将过期" : "过期" }}</span>
        </template>
      </el-table-column>

      <el-table-column label="当前状态">
        <template #default="scope">
          <el-switch :width="58" v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt @change="switchProcess(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注">
        <template #default="scope">
          <el-tooltip effect="dark" placement="top-start">
            <template #content>
              <div style="max-width: 500px;">
                {{ scope.row.remark }}
              </div>
            </template>
            <el-text truncated>
              {{ scope.row.remark }}
            </el-text>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="newLastModified" label="更新时间" align="center" width="200" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="choseNetwork(scope.row)">网络配置</el-button>
          <el-button link type="primary" @click="choseEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" @click="choseEditCheck(scope.row)">密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :limit="searchFrom.pageSize" :page="searchFrom.pageNum"
      @pagination="handleCurrentChange">
    </Pagination>
    <AddService :dialogVisible="dialogVisible" :listItem="publicItem" @handleServiceClose="handleServiceClose"
      @handleServiceSure="handleServiceSure"></AddService>
    <SiteNetwork :networkVisible="networkVisible" @handleNetworkClose="handleNetworkClose" :listItem="publicItem">
    </SiteNetwork>
    <CheckAssemble :AssembleVisible="AssembleVisible" :listItem="publicItem" @handleAssembleClose="handleAssembleClose"
      @handleAssembleSure="handleAssembleSure" :typeAssemble="1"></CheckAssemble>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import AddService from "./components/AddService.vue";
import SiteNetwork from "./components/siteNetwork.vue";
import CheckAssemble from "./components/checkAssemble.vue";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const { sys_status_type } = proxy.useDict("sys_status_type"); //服务器IP类型
const dialogVisible = ref(false); //默认不显示弹窗
const networkVisible = ref(false); //默认不显示弹窗
const AssembleVisible = ref(false); //默认不显示弹窗

const sys_provider = ref([]); //服务商
const sys_account = ref([]); //服务商账号
const sys_country = ref([]); //国家
const switchLoading = ref(true);
const loading = ref(true)

const searchFrom = ref({
  pageNum: 1,
  pageSize: 20,
  param: {
    cloudServerProviderId: "", //服务商
    cloudServerId: "", //服务商账号
    countryId: "", //国家
    status: null, //状态
    newCountryId: ''
  },
}); //搜索参数
const publicItem = ref({}); //公共赋值数据
const total = ref(0);
const tableData = ref([]);
onMounted(() => {
  getList();
  getSet();
});
const getList = () => {
  site.general
    .siteserverList({
      data: searchFrom.value,
    })
    .then((res) => {
      switchLoading.value = false;
      loading.value = false;
      if (res.data?.length) {
        res.data = res.data.map((code) => {
          return {
            ...code,
            current: getCurrent(code),
            newInitiate: proxy.DateTime(code.startTime),
            newExpire: proxy.DateTime(code.expireTime),
            newLastModified: proxy.DateTime(code.lastModified)
            ,
          };
        });
      }
      total.value = res.total;
      tableData.value = res.data;
    });
};
// 搜索
const handleSearch = () => {
  let newCountry = searchFrom.value.param.newCountryId
  const newMatch = newCountry.match(/([-+]\d*\.?\d+)/);
  searchFrom.value.param.countryId = newCountry.slice(0, newMatch.index);
  getList();
};
// 重置
const handleReset = () => {
  proxy.resetForm("serveRef");
  getList();
};
//网络配置
const choseNetwork = (row) => {
  publicItem.value = row;
  networkVisible.value = true;
};
//网络配置取消
const handleNetworkClose = () => {
  networkVisible.value = false;
  getList();

};
// 新增
const addService = () => {
  publicItem.value = {};
  dialogVisible.value = true;
};
// 编辑
const choseEdit = (row) => {
  publicItem.value = row;
  dialogVisible.value = true;
};
const switchProcess = (rowItem) => {
  if (switchLoading.value) return;
  proxy.$modal
    .confirm("是否确认修改此数据类型？")
    .then(() => {
      site.general
        .siteserverUpdatestatus({
          pathParams: {
            id: rowItem.id,
          },
          params: {
            status: rowItem.status,
          },
        })
        .then((res) => {
          if (res.code === 200) {
            getList();
            proxy.$modal.msgSuccess(res.message);
          }
        });
    })
    .catch((err) => {
      if (rowItem.status) {
        return (rowItem.status = 0);
      } else {
        return (rowItem.status = 1);
      }
    });
};
const handleDelete = (rowItem) => {/** 删除按钮操作 */
  var newArray = [];
  newArray.push(rowItem.id);
  proxy.$modal.confirm("是否确认删除此数据类型？").then(() => {
    site.general
      .siteserverRemovebatchbyids({
        data: {
          ids: newArray,
        },
      })
      .then((res) => {
        if (res.code === 200) {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        }
      });
  });
};
const choseEditCheck = (row) => {
  publicItem.value = row;
  let from = {
    id: row.id,
    username: userStore.name,
    password: null
  }
  proxy.$modal.prompt(from.password, `账号：${userStore.name}`, '内容不能为空', '请输入密码').then(res => {
    from.password = res.value
    // serverAccount//用户名
    if (row.pwdType === 'pwd') {
      site.general.siteserverViewpassword({
        data: from
      }).then((res) => {
        if (res.code === 200) {
          publicItem.value = {
            ...row,
            username: row.serverAccount,
            password: res.data.password
          }
          AssembleVisible.value = true
        }
      }).catch(err => {
        choseEditCheck(row)
      })

    } else {
      site.general.siteserverViewsecretkey({
        data: from
      }).then((res) => {
        if (res.code === 200) {
          publicItem.value = {
            ...row,
            username: row.serverAccount,
            password: res.data.password
          }
          AssembleVisible.value = true
        }
      }).catch(err => {
        choseEditCheck(row)
      })
    }
  })
}
const handleAssembleSure = () => {
  AssembleVisible.value = false;
  getList();
};
const handleAssembleClose = () => {// 取消事件
  AssembleVisible.value = false;
};



const handleServiceSure = () => {// 确定事件
  dialogVisible.value = false;
  getList();
};

const handleServiceClose = () => {// 取消事件
  dialogVisible.value = false;
};
const getSet = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {},
  };

  site.general
    .siteserverproviderList({  // 服务商
      data: from,
    })
    .then((res) => {
      sys_provider.value = res.data;
    });

  site.general
    .sitecloudserverList({  // 服务商账号
      data: from,
    })
    .then((res) => {
      sys_account.value = res.data;
    });
  getCountry(from);
};
const getCountry = async (from) => {/** 查询类别管理列表 */
  site.country
    .countryList({
      data: from,
    })
    .then((res) => {
      res.data = addLevelToTree(res.data);
      sys_country.value = res.data;
    });
};

const addLevelToTree = (tree, parentLevel = 0) => {
  return tree.map((item) => ({
    ...item,
    newId: `${item.id}-${parentLevel + 1}`,
    children: item.children
      ? addLevelToTree(item.children, parentLevel + 1)
      : undefined,
  })
  )
}
// 分页
const handleCurrentChange = (newPage) => {
  searchFrom.value.pageNum = newPage.page;
  searchFrom.value.pageSize = newPage.limit;
  getList();
};
var defaultProps = reactive({
  children: "children",
  label: "description",
  value: "newId", // 指定 id 作为 value 属性
});
const rowStyle = ({ row }) => {
  if (row.current === 'danger') {
    return { color: "#f56c6c" }; // 设置背景色和文本颜色
  } else if (row.current === 'warning') {
    return { color: "#E6A23C" }; // 设置背景色和文本颜色
  } else {
    return {};
  }
};
const getCurrent = (row) => {
  let CurrentTime

  let futureTimestamp;
  let daysToAdd = 14;
  let currentTimestamp = new Date().getTime();
  const millisecondsInADay = 24 * 60 * 60 * 1000;
  CurrentTime = Math.floor(currentTimestamp / 1000);
  if (CurrentTime > row.expireTime) return 'danger'//当前时间大于过期时间
  /**
   * 当前时间+14天《=过期时间 false
   * 当前时间+14天=过期时间 false
   * 当前时间+14天>过期时间 true
  */
  futureTimestamp = currentTimestamp + daysToAdd * millisecondsInADay;
  futureTimestamp = Math.floor(futureTimestamp / 1000);
  // console.log(row.expireTime, "14天后的日期是: ", futureTimestamp);
  if (futureTimestamp < row.expireTime) {
    return '';
  } else if (currentTimestamp > row.expireTime) {
    return 'warning';
  } else {
    return '';
  }
};
</script>